﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Threading.Tasks;
using instanceExcel = Microsoft.Office.Interop.Excel;

namespace Util
{
    public class Excel
    {
        private instanceExcel.Application ApExcel;

        private instanceExcel.Worksheet sheet = null;

        private object opc = Type.Missing;

        private string pathFile = null;

        public Excel()
        {

        }

        public Excel(string file)
        {
            this.open(file);
        }

        public void open(string file)
        {

            if (this.ApExcel != null)
            {

                this.close();

            }

            this.ApExcel = new instanceExcel.Application();

            this.ApExcel.Workbooks.Open(file);

            this.pathFile = file;

        }

        public void close()
        {

            if (this.ApExcel != null)
            {

                this.ApExcel.Quit();

                this.ApExcel.Workbooks.Close();

            }

        }

        public void setSheet(int hoja)
        {

            this.sheet = this.ApExcel.ActiveWorkbook.Sheets[hoja];

            this.sheet.Select(this.opc);

        }

        public string getValue(string celda)
        {

            instanceExcel.Range range = this.sheet.get_Range(celda);

            string resultado = range.Value;

            return resultado;

        }

        public object[,] getValues(string inicio, string fin)
        {

            instanceExcel.Range range = this.sheet.get_Range(inicio, fin);

            object[,] resultado = range.Cells.Value;

            return resultado;

        }

        public void setValue(int x, int y, string value)
        {

            this.sheet.Cells[x, y] = value;

            this.ApExcel.SaveWorkspace();

        }

        public void addSheet(string name)
        {

            instanceExcel.Sheets hojas = this.ApExcel.ActiveWorkbook.Sheets;

            object After = hojas[hojas.Count];

            instanceExcel.Worksheet newSheet = (instanceExcel.Worksheet)this.ApExcel.Worksheets.Add();

            newSheet.Name = name;

            newSheet.Move(this.opc, After);

            this.ApExcel.SaveWorkspace();

        }

        public void create(string pathFile)
        {

            this.ApExcel = new instanceExcel.Application();

            instanceExcel.Workbook libro = this.ApExcel.Workbooks.Add(this.opc);

            libro.SaveAs(pathFile);

            this.close();

        }

    }
}